<template>
    <div class="order-shipping">
        <h2>Shipping</h2>
        <div class="order-address">
            <!-- 标题 -->
            <div class="address-tabs" v-if="address.list.length > 0">
                <a @click="setTab('list')" :class="{ active: address.tab == 'list' }">Address book ({{address.list.length}})</a>
                <a @click="setTab('edit')" :class="{ active: address.tab == 'edit' }">New address</a>
            </div>

            <ul class="address-list" v-if="address.tab == 'list'">
                <li v-for="item in address.list" :class="{ active: item.id == address.active }" :key="item.id" @click="setAddressActive(item)">

                    <h3 :title="item.first_name">{{ item.first_name }}</h3>
                    <p>
                        <img src="@/assets/images/setting/setting-address-phone.png" alt="">
                        <span>Phone:</span>
                        <strong v-text="item.phone"></strong>
                    </p>
                    <p>
                        <img src="@/assets/images/setting/setting-address-email.png" alt="">
                        <span>Email:</span>
                        <strong v-text="item.email"></strong>
                    </p>
                    <p>
                        <img src="@/assets/images/setting/setting-address-address.png" alt="">
                        <span>Address1:</span>
                        <strong>
                            <em v-text="item.street"></em>
                            <em v-text="[item.city,item.state,item.country].filter(i=>i).join(',')"></em>
                        </strong>
                    </p>
                    <p v-if="item.district != ''">
                        <img src="@/assets/images/setting/setting-address-address.png" alt="">
                        <span>Address2:</span>
                        <strong v-text="item.district"></strong>
                    </p>
                    <p>
                        <img src="@/assets/images/setting/setting-address-postcode.png" alt="">
                        <span>Post code:</span>
                        <strong v-text="item.post_code"></strong>
                    </p>

                    <cite><svg-icon name="address-select" /></cite>

                </li>
            </ul>

            <div class="address-input" v-else-if="form">
                <CommonAddressForm ref="form" v-model="form" @submit="doNext($event)" @validate="formForbid = !!$event" />
                <h6 v-if="address.list.length < 4 && shopId <= 0" @click="insertAddress($event)">Save to address book</h6>
            </div>

            <UxLoading :loading="loading_save" />

        </div>

        <div class="order-shipping-btn">
            <button @click="$router.go(-1)">Back</button>
            <button type="primary" :class="{disabled:forbid}" @click="doNext($event)">
                <span>Order</span>
                <UxLoading size="24px" :loading="loading_next" />
            </button>
        </div>
    </div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
    name: "OrderShipping",
    layout: "layout-logined",
    data () {
        return {
            loading_save: true,
            loading_next: false,
            form: null,
            formForbid: true, // 禁止下一步
        };
    },
    computed: {
        ...mapGetters("order", {
            shopId: "getShopId",
            address: "getAddress",
            product: "getProduct",
            pricing: "getPricing",
            logistics: "getLogistics",
            addressActive: "getAddressActive",
        }),

        // 是否允许下一步
        forbid () {
            if (this.address.tab == 'list') {
                return !this.addressActive;
            } else {
                return this.formForbid;
            }
        },
    },
    watch: {
        form: {
            deep: true,
            handler (newval) {
                const address = { ...newval }
                this.$store.commit("order/SET_ADDRESS_EDIT", address)
            }
        },
    },
    methods: {
        addressValidate (forbid) {
            this.forbid = forbid;
        },
        mathRound (value, n) {
            n = n === undefined ? 1 : n;
            let bei = Math.pow(10, n);
            let res = Math.round(value * bei) / bei;
            return +parseFloat(res.toPrecision(12));
        },
        setTab (type) {

            if (type == 'list') {
                if (this.address.list.length <= 0) {
                    // 没有数据只能选
                    this.form = { ...this.address.edit };

                    // 先禁用掉
                    // this.form.country_code = this.form.country_code || "US";
                    this.$store.commit("order/SET_ADDRESS_TAB", 'edit');

                } else if (this.address.active) {

                    const select = this.address.list.filter(i => i.id == this.address.active);
                    const active = select[0] || this.address.list[0];

                    this.$store.commit("order/SET_ADDRESS_ACTIVE", active.id);
                    this.$store.commit("order/SET_ADDRESS_TAB", 'list');
                } else {
                    this.$store.commit("order/SET_ADDRESS_ACTIVE", this.address.list[0].id);
                    this.$store.commit("order/SET_ADDRESS_TAB", 'list');
                }
            } else {

                this.form = { ...this.address.edit };
                // this.form.country_code = this.form.country_code || "US";
                this.$store.commit("order/SET_ADDRESS_TAB", 'edit');
            }
        },

        // 选中地址
        setAddressActive (item) {
            this.$store.commit("order/SET_ADDRESS_ACTIVE", item.id);
        },

        // 保存地址
        insertAddress (event) {

            event.preventDefault();
            event.stopPropagation();


            if (this.formForbid) {
                this.$refs.form.tipsValidator().catch(error => { })
            } else {
                this.loading_save = true;

                this.$http("address.insert", this.address.edit).then(response => {
                    if (response.code === 0) {
                        return this.$store.dispatch("order/setShippingInit")
                    } else {
                        return Promise.reject({ code: 400, msg: "Failed to add address, please try again" })
                    }
                }).then(response => {

                    const list = this.address.list;
                    const last = list[list.length - 1] || {};
                    this.loading_save = false;
                    // 选中最后一个
                    this.$store.commit("order/SET_ADDRESS_ACTIVE", last.id);
                    // 切换到list
                    this.$store.commit("order/SET_ADDRESS_TAB", 'list');
                    // 清空编辑的数据
                    this.$store.commit("order/SET_ADDRESS_EDIT", null);

                }).catch(error => {
                    const result = error || { msg: "The address is incorrect, please check completely and try again" }
                    this.$uxMessage.error(result.msg || 'Failed to save address book');
                    this.loading_save = false;
                })
            }

        },

        //下一步
        doNext (event) {
            // 这里有问题，计算价格要先计算用户的等级优惠和优惠劵，再结合物流地址才能计算税费
            // this.$router.push("/order/confirm");

            event.preventDefault();
            event.stopPropagation();

            if (this.address.tab == 'edit' && this.formForbid) {
                this.$refs.form.tipsValidator().catch(error => { })
            } else {
                this.loading_next = true
                this.$store.dispatch("order/setConfirmInit").then(res => {
                    this.loading_next = false;
                    this.$router.push("/order/confirm");
                    return Promise.resolve()
                }).catch(error => {
                    this.loading_next = false;
                    this.$uxMessage.error(error.msg || "Failed to get your address");
                })
            }
        },

    },
    mounted () {

        if (this.address.loaded) {
            this.loading_save = false;
            this.setTab(this.address.tab);
        } else {
            this.loading_save = true
            this.$store.dispatch("order/setShippingInit").then(res => {
                this.setTab(this.address.tab);
                this.loading_save = false;
            }).catch(error => {
                this.loading_save = false;
            })
        }
    },
};
</script>
<style lang="scss" scoped>
.order-shipping {
    display: flex;
    flex-direction: column;
    padding-bottom: 96px;
    max-width: 1080px;
    margin: 0 auto;

    & > h2 {
        margin: 40px 0;
        font-size: 32px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 40px;
    }
}

.order-address {
}

.address-tabs {
    display: inline-flex;
    position: relative;
    margin-right: auto;
    margin-top: -10px;
    margin-bottom: 36px;

    &::before {
        content: '';
        position: absolute;
        left: 0;
        bottom: 0;
        right: 0;
        height: 1px;
        background-color: #dcdcdc;
    }

    a {
        position: relative;
        border: none;
        line-height: 40px;
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #555555;
        padding: 0;
        cursor: pointer;

        & + a {
            margin-left: 20px;
        }
        &::after {
            content: '';
            position: absolute;
            left: 0;
            bottom: 0;
            right: 0;
            height: 2px;
            border-radius: 2px;
            background-color: transparent;
        }

        &:hover {
            &::after {
                background-color: #f6b2cd;
            }
        }

        &.active {
            color: #ea4c89;

            &::after {
                background-color: #ea4c89;
            }
        }

        & + button {
            margin-left: 20px;
        }
    }
}

.address-list {
    flex-direction: row;
    flex-wrap: wrap;
    display: flex;
    justify-content: space-between;
    margin: -10px -10px 0;

    li {
        width: calc(50% - 20px);
        margin: 10px;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #e6e6e6;
        position: relative;
        box-sizing: border-box;
        padding: 38px;
        cursor: pointer;
        transition: all 0.2s;

        h3 {
            font-size: 22px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 26px;
            margin-bottom: 24px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-right: 40px;
        }

        p {
            display: flex;
            & + p {
                margin-top: 12px;
            }
            img {
                width: 16px;
                height: 16px;
            }
            span {
                margin-left: 4px;
                width: 68px;
                height: 16px;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #555555;
                line-height: 16px;
            }
            strong {
                margin-left: 12px;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #000000;
                line-height: 16px;
                display: block;
                white-space: normal;
                word-break: break-word;
                em {
                    display: block;
                }

                em + em {
                    margin-top: 8px;
                }
            }
        }

        cite {
            position: absolute;
            right: 38px;
            top: 38px;
            width: 28px;
            height: 28px;
            background: #f6f6f6;
            border-radius: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #d1d1d1;
            transition: all 0.2s;
            svg {
                width: 16px;
                height: 16px;
            }
        }

        &:hover {
            box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.08);
            cite {
                color: rgba(#008452, 0.5);
            }
        }

        &.active {
            cursor: default;
            &:hover {
                box-shadow: inherit;
            }
            cite {
                background: #008452;
                color: #fff;
            }
        }
    }
}

.address-input {
    .address-form {
        margin: 0 -24px;
    }
    & > h6 {
        display: inline-block;
        margin: 10px 24px 40px auto;
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #087196;
        line-height: 18px;
        cursor: pointer;
        text-decoration: underline;

        &:hover {
            text-decoration: underline;
            color: #287e9c;
        }
    }
}

.order-shipping-btn {
    position: fixed;
    width: 100vw;
    left: 0;
    bottom: 0;
    height: 72px;
    background: #ffffff;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;

    &::before {
        content: '';
        display: block;
        background: #e6e6e6;
        width: 100%;
        height: 1px;
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
    }

    & > button {
        height: 40px;
        width: 108px;

        &:nth-child(2) {
            position: relative;
            width: 180px;
            margin-left: 12px;
        }
    }
}
</style>
